package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.bean.CodeGenerator;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.mapper.CheckInMapper;
import com.zzyl.nursing.service.ICheckInService;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.Type;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

/**
 * 入住Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-05-27
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;

    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 入住申请
     * @param dto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void apply(CheckInApplyDto dto) {
        //查询老人是否已存在系统
        String idCardNo = dto.getCheckInElderDto().getIdCardNo();
        Elder one = Db.lambdaQuery(Elder.class)
                .eq(Elder::getIdCardNo, idCardNo)
                .eq(Elder::getStatus, 1)
                .one();
        if(one != null){
        //    更新老人信息
            throw new BaseException("老人已入住");
        }
        //1.往elder表中加入信息，注意有三个字段为空status,bedNumber,bedId
        Elder elder = BeanUtil.copyProperties(dto.getCheckInElderDto(), Elder.class);
        elder.setStatus(1);
        Long bedId = dto.getCheckInConfigDto().getBedId();
        Bed bed = new Bed();
        bed.setId(bedId);
        //更新bed的状态
        Db.lambdaUpdate(Bed.class).set(Bed::getBedStatus, 1).update();
        elder.setBedNumber(Db.getById(bed, Bed.class).getBedNumber());
        elder.setBedId(bedId);
        Db.saveOrUpdate(elder);
        Long elderId = elder.getId();

        //2.往checkIn表中加入信息
        CheckIn checkIn = BeanUtil.copyProperties(dto.getCheckInConfigDto(), CheckIn.class);
        checkIn.setElderName(elder.getName());
        checkIn.setElderId(elderId);
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setBedNumber(elder.getBedNumber());
        checkIn.setStatus(0);
        checkIn.setSortOrder(0);
        checkIn.setRemark(JSONUtil.toJsonStr(dto.getElderFamilyDtoList()));
        Db.saveOrUpdate(checkIn);
        Long checkInId = checkIn.getId();

        //3.往表中加入信息
        CheckInConfig checkInConfig = BeanUtil.copyProperties(dto.getCheckInConfigDto(), CheckInConfig.class);
        checkInConfig.setCheckInId(checkInId);
        checkInConfig.setSortOrder(0);
        Db.saveOrUpdate(checkInConfig);

        //4.往contract表中插入信息
        Contract contract = BeanUtil.copyProperties(dto.getCheckInContractDto(), Contract.class);
        BeanUtil.copyProperties(dto.getCheckInConfigDto(),contract);
        // 生成合同编号
        String contractNo = "HT" + CodeGenerator.generateContractNumber();
        contract.setContractNumber(contractNo);
        contract.setElderId(elderId);
        contract.setElderName(elder.getName());
        contract.setStartDate(dto.getCheckInConfigDto().getStartDate());
        contract.setEndDate(dto.getCheckInConfigDto().getEndDate());
        contract.setStatus(0);
        contract.setSortOrder(0);
        Db.saveOrUpdate(contract);
    }

    /**
     * 入住详情
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public CheckInDetailVo detail(Long id) {
        CheckIn checkIn = Db.lambdaQuery(CheckIn.class).eq(CheckIn::getId, id).one();
        Long elderId = checkIn.getElderId();
        //查询老人信息并分装
        Elder elder = Db.lambdaQuery(Elder.class)
                .eq(Elder::getId, elderId)
                .one();
        CheckInElderVo checkInElderVo = BeanUtil.copyProperties(elder, CheckInElderVo.class);
        int nowYear = LocalDateTime.now().getYear();
        checkInElderVo.setAge(nowYear - Integer.parseInt(elder.getBirthday().substring(0, 4)));

        //获取家属信息
        String remark = checkIn.getRemark();
        Gson gson = new Gson();
        Type type = new TypeToken<List<ElderFamilyVo>>() {}.getType();
        List<ElderFamilyVo> elderFamilyVoList = gson.fromJson(remark, type);

        //获取入住配置
        CheckInConfigVo checkInConfigVo = BeanUtil.copyProperties(checkIn, CheckInConfigVo.class);
        CheckInConfig checkInConfig = Db.lambdaQuery(CheckInConfig.class).eq(CheckInConfig::getCheckInId, id).one();
        BeanUtil.copyProperties(checkInConfig,  checkInConfigVo);

        //获取合同信息
        Contract contract = Db.lambdaQuery(Contract.class).eq(Contract::getElderId, elderId).one();

        return CheckInDetailVo.of(checkInElderVo, elderFamilyVoList, checkInConfigVo, contract);
    }
}
